package pbx.service;

import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import pbx.model.QueueLog;


@Stateless
public class QueueLogService {

	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
	
	
	public QueueLog save(QueueLog queuelog) {
		em.persist(queuelog);
		return queuelog;   
	}
	
	public QueueLog update(QueueLog queuelog) {
		return em.merge(queuelog);
	}
	
	@SuppressWarnings("unchecked")
    public List<QueueLog> listByCallId(String callid) {
    	Query query = em.createQuery("SELECT e FROM QueueLog e WHERE e.callid = :callid  ORDER BY e.time ASC " );
    	query.setParameter("callid", callid);
    	return query.getResultList();   
    }

    public void changeBilledByDateRange(Date startdate, Date enddate, Boolean status, Integer queueId){
    
		String sql = "UPDATE QueueLog e SET e.process = null WHERE e.time BETWEEN :startdate AND :enddate ";
		if(queueId!=null){
			sql = sql + " AND e.name=:name ";
		}
		Query query = em.createQuery(sql);
		query.setParameter("startdate", startdate);
		query.setParameter("enddate", enddate);
		if(queueId!=null){
			query.setParameter("queueId", String.valueOf(queueId));
		}
        query.executeUpdate();  
    }
    
    public void setStatus(String uniqueid, Boolean status){        
    	String sql = "UPDATE QueueLog e SET e.billed = :status  WHERE e.uniqueid = :uniqueid ";
    	Query query = em.createQuery(sql);
    	query.setParameter("status", status);
    	query.setParameter("uniqueid", uniqueid);
        query.executeUpdate();  
    }

    @SuppressWarnings("unchecked")
    public List<QueueLog> listForProcess(Integer size) {
    	Query query = em.createQuery("SELECT e FROM QueueLog e WHERE e.process is null AND e.event = :event ORDER BY e.time ASC ");
    	query.setParameter("event", "ENTERQUEUE");
    	query.setMaxResults(size);
    	return query.getResultList();   
    }

    
}

